<?php
class Aearning {
	const MAX  = 500; //每日提现最多提取500
	const CMAX = 2000;//每日提现最多提取2000
	const MIN  = 20;  //每次提现不得低于20
	public static function main($funcode) {
		sview::verify(true, true);
		switch ($funcode) {
			case 1:
				self::__getwithdraw();
				break;
			case 2:
				self::__dowithdraw();
				break;
			case 3:
				self::__dosetbank();
				break;
			case 4:
				self::__getcredits();
				break;
			case 5:
				self::__addpaypal();
				break;
			case 6:
				self::__getpaypal();
				break;
			case 7:
				self::__addcard();
				break;
			case 8:
				self::__getcard();
				break;
			case 9:
				self::__withdraw();
				break;
			default:
				sview::$view->assign_error(404, lang::text(404));
		}
	}
	
	//获取提现信息列表3-6-1
	private static function __getwithdraw() {
		$start = intval(sview::$ctrl['offset']);
		$limit = intval(sview::$ctrl['limit']);
		if ($limit > 30) {
			$limit = 15;
		}
		$acl    = acl::getinst('vedio');
		$userid = $acl->user['id'];
		$where  = array('userid'=>$userid);
		$stime  = isset(sview::$ctrl['startime'])? strtotime(sview::$ctrl['startime'].' 00:00:00'):0;
		$etime  = isset(sview::$ctrl['endtime'])? strtotime(sview::$ctrl['endtime'].' 23:59:59'):0;
		if ($stime) {
			$where[] = array('stime', $stime, orm::OP_GE);
		}
		if ($etime) {
			$where[] = array('stime', $etime, orm::OP_LT);
		}
		$field = 'sn,addtime,type,money,status,paystate,paytype';
		$data  = model::load('live/withdraw')->get_only_list($start, $limit, $where, $field, 'id', orm::DESC);
		foreach ($data as &$item) {
			if ($item['paytype'] > 0) {
				if ($item['paystate'] > 2) {
					$item['status'] = 0;
				} else {
					$item['status'] = $item['paystate'];
				}
			}
			$item['money']   = $item['money']/api_uc::CANRATIO;
		}
		sview::$view->assign_by_ref('datasets', $data);
		sview::$view->display();
	}
	
	//提交申请提现3-6-2
	private static function __dowithdraw() {
		$acl    = acl::getinst('vedio');
		$userid = $acl->user['id'];
		$where  = array('userid'=>$userid);
		$draw   = model::load('live/withdraw')->get_item($where, 'status,stime', 'id', orm::DESC);
		if ($draw) {
			if (!$draw['status']) {
				sview::$view->assign_error(60033, lang::text(60033));
			}
			if(date('Ymd', $draw['stime']) == date('Ymd', config::$nowtime)) {
				sview::$view->assign_error(60034, lang::text(60034));
			}
		}
		$where  = array('userid'=>$userid, 'inuse'=>1, 'status'=>1);
		$bank   = model::load('live/depositbank')->get_item($where);
		if (!$bank) {
			sview::$view->assign_error(60028, lang::text(60028));
		}
		$money  = intval(sview::$ctrl['money']);
		if ($money < 20) {
			sview::$view->assign_error(60036, lang::text(60036));
		}
		$anchor = model::load('live/anchor')->get_one($userid);
		$valid  = ($anchor['earningcoins'] - $anchor['depositcoins']) / api_uc::STARRATIO;
		if ($money > $valid) {
			sview::$view->assign_error(60035, lang::text(60035));
		}
		$sn     = date('YmdHis').randme::rand_str(6, 2);
		$field  = array('userid'=>$userid, 'depositid'=>$bank['id'], 'visa'=>'', 'sn'=>$sn, 'type'=>1,
			'coins'=>$money*api_uc::STARRATIO, 'money'=>$money*api_uc::CANRATIO, 'addtime'=>config::$nowtime,
			'stime'=>config::$nowtime);
		model::load('live/withdraw')->new_one($field);
		sview::$view->display();
	}
	
	//设置银行卡信息 3-6-3
	private static function __dosetbank() {
		$acl    = acl::getinst('vedio');
		$userid = $acl->user['id'];
		$where  = array('userid'=>$userid, 'inuse'=>1);
		$bank   = model::load('live/depositbank')->get_item($where, 'id,status,stime', 'id', orm::DESC);
		if ($bank && !$bank['status']) {
			sview::$view->assign_error(60029, lang::text(60029));
		}
		if($bank && (date('Ymd', $bank['stime']) == date('Ymd', config::$nowtime))){
			sview::$view->assign_error(60030, lang::text(60030));
		}
		$firstname = htmlspecialchars(trim(sview::$ctrl['firstname']));
		$lastname  = htmlspecialchars(trim(sview::$ctrl['lastname']));
		$birthday  = sview::$ctrl['birthday'];
		if (!verify::is_date($birthday)) {
			sview::$view->assign_error(80031, lang::text(80031));
		}
		$country   = htmlspecialchars(trim(sview::$ctrl['country']));
		$currency  = htmlspecialchars(trim(sview::$ctrl['currency']));
		$account   = htmlspecialchars(sview::$ctrl['bankaccount']);
		$tranum    = sview::$ctrl['tranum'];
		if (!is_numeric($tranum) || strlen($tranum) != 5) {
			sview::$view->assign_error(60031, lang::text(60031));
		}
		$insnum    = sview::$ctrl['insnum'];
		if (!is_numeric($insnum) || strlen($insnum) != 3) {
			sview::$view->assign_error(60032, lang::text(60032));
		}
		$url       = sview::$ctrl['photo'];
		if (!$url) {
			sview::$view->assign_error(60003, lang::text(60003));
		}
		$field     = array('userid'=>$userid, 'inuse'=>1, 'first_name'=>$firstname, 'last_name'=>$lastname, 'birthday'=>$birthday, 
			'country'=>$country, 'currency'=>$currency, 'bank_account'=>$account, 'transit_number'=>$tranum, 
			'instititional_number'=>$insnum, 'photo'=>$url, 'photo_id'=>$url, 'stime'=>config::$nowtime);
		model::load('live/depositbank')->new_one($field);
		sview::$view->display();
	}
	
	//获取收益信息明细
	private static function __list($start, $limit, $userid) {
		$reftype= isset(sview::$ctrl['reftype'])? (int)sview::$ctrl['reftype']:0;
		$stime  = isset(sview::$ctrl['startime'])? strtotime(sview::$ctrl['startime'].' 00:00:00'):0;
		$etime  = isset(sview::$ctrl['endtime'])? strtotime(sview::$ctrl['endtime'].' 23:59:59'):0;
		$morm = model::load('live/moneyflow');
		$skey = 'IC'.md5(json_encode(func_get_args()).$morm->get_cache_ver());
		$list = cache::getinst()->get($skey);
		if (!$list) {
			$where  = ' WHERE anchorid = '.$userid;
			if ($reftype > 0) {
				$where  .= ' AND reftype = '.$reftype;
			}
			if ($stime) {
				$where  .= ' AND stime >= '.$stime;
			}
			if ($etime) {
				$where  .= ' AND stime < '.$etime;
			}
			$tables = model::load('live/moneyflow')->db_table();
			$unions = array();
			$fields = 'userid,reftype,refid,earning,nums,stime';
			foreach ($tables as $table) {
				$unions[] = '(SELECT '.$fields.' FROM '.$table.$where.' ORDER BY id DESC)';
			}
			$sql    = implode(' UNION ', $unions);
			$list   = $morm->get_orm()->get_list('SELECT * FROM ('.$sql.') as tmp', $start, $limit);
			cache::getinst()->set($skey, $list);
		}
		return $list;
	}
	
	//获取礼物收益列表3-6-4
	private static function __getcredits() {
		$start = intval(sview::$ctrl['offset']);
		$limit = intval(sview::$ctrl['limit']);
		if ($limit > 30) {
			$limit = 15;
		}
		$acl    = acl::getinst('vedio');
		$userid = $acl->user['id'];
		$data   = self::__list($start, $limit, $userid);
		if ($data) {
			$uorm = model::load('live/userinfo');
			$gorm = model::load('live/gift');
			$dorm = model::load('live/guard');
			foreach ($data as &$item) {
				if ($item['userid'] < 1) {
					$item['nickname'] = 'System';
				} else {
					$user = $uorm->set_devision($item['userid'])->get_one($item['userid']);
					$item['nickname'] = htmlspecialchars_decode($user['nickname']);
				}
				if ($item['reftype'] == 1) {
					$row = $gorm->get_one($item['refid']);
					$item['refname'] = $row['name'];
					$item['iconsrc'] = $row['iconsrc'];
				} else if ($item['reftype'] == 4) {
					$row = $dorm->get_one($item['refid']);
					$item['refname'] = $row['name'];
					$item['iconsrc'] = $row['iconsrc'];
					$time            = ($item['refid']==1)? lang::text(60038):lang::text(60039);
					$item['nums']    = $item['nums'].'/'.$time;
				} else if ($item['reftype'] == 5 || $item['reftype'] == 7) {
					$item['refname'] = DDmoneyflow::$rtype[$item['reftype']];
					$item['iconsrc'] = '';
				} else {
					$item['refname'] = 'unknown';
					$item['iconsrc'] = '';
				}
				$item['userid']  = (int)$item['userid'];
				$item['reftype'] = (int)$item['reftype'];
				$item['refid']   = (int)$item['refid'];
				$item['earning'] = (float)$item['earning'];
				$item['nums']    = (int)$item['nums'];
				$item['stime']   = (int)$item['stime'];
			}
		}
		sview::$view->assign_by_ref('datasets', $data);
		sview::$view->display();
	}
	
	//提交修改paypal 3-6-5
	private static function __addpaypal() {
		$acl    = acl::getinst('vedio');
		$email  = trim(sview::$ctrl['email']);
		if (!verify::is_email($email)) {
			sview::$view->assign_error(80003, lang::text(80003));
		}
		$userid = $acl->user['id'];
		$user   = model::load('live/userinfo')->set_devision($userid)->get_one($userid);
		$orm    = model::load('live/payment');
		$where  = array('paypal'=>$email);
		$item   = $orm->get_item($where);
		if ($item) {
			sview::$view->assign_error(80126, lang::text(80126));
		}
		$item   = $orm->get_one($userid);
		if (empty($item['paypal'])) {
			$firstname = trim(sview::$ctrl['firstname']);
			$lastname  = trim(sview::$ctrl['lastname']);
		} else {
			$firstname = $item['firstname'];
			$lastname  = $item['firstname'];
		}
		$res    = api_paypal::account($user['token'], $email, $firstname, $lastname);
		if ($res['result'] != '000' || !empty($res['value']['error'])) {
			sview::$view->assign_error(80123, lang::text(80123));
		}
		$row    = $orm->get_one($userid);
		$field  = array('firstname'=>$firstname, 'lastname'=>$lastname, 'paypal'=>$email);
		if ($row) {
			$orm->save($userid, $field);
		} else {
			$field['userid']   = $userid;
			$field['birthday'] = '0000-00-00';
			$orm->new_one($field);
		}
		sview::$view->display();
	}
	
	//获取paypal 3-6-6
	private static function __getpaypal() {
		$acl    = acl::getinst('vedio');
		$userid = $acl->user['id'];
		$payment= model::load('live/payment')->get_one($userid);
		$data   = array('paypal'=> '', 'firstname'=>'', 'lastname'=>'');
		if ($payment['paypal']) {
			$data = array('paypal'=>$payment['paypal'], 'firstname'=>$payment['firstname'], 'lastname'=>$payment['lastname']);
		}
		sview::$view->assign_by_ref('datasets', $data);
		sview::$view->display();
	}
	
	//添加编辑银行卡 3-6-7
	private static function __addcard() {
		$acl    = acl::getinst('vedio');
		$userid = $acl->user['id'];
		$payment= model::load('live/payment')->get_one($userid);
		$token  = trim(sview::$ctrl['stripeToken']);
		if (!$token) {
			sview::$view->assign_error(80009, lang::text(80009));
		}
		$type      = 'individual';
		$firstname = trim(sview::$ctrl['firstname']);
		$lastname  = trim(sview::$ctrl['lastname']);
		//验证屏蔽关键词
		$lang = lang::load('filter.php');
		if ($firstname) {
			$res = api_im::filter(2, $firstname);
			if ($res && $res['ResultContent'] == 1) {
				sview::$view->assign_error(80088, lang::replace(80088, $lang['firstname']));
			}
		}
		if ($lastname) {
			$res = api_im::filter(2, $lastname);
			if ($res && $res['ResultContent'] == 1) {
				sview::$view->assign_error(80088, lang::replace(80088, $lang['lastname']));
			}
		}
		$birthday  = sview::$ctrl['birthday'];
		//验证通过就不要传birthday
		if (!verify::is_date($birthday) && $payment['status'] != 1) {
			sview::$view->assign_error(80031, lang::text(80031));
		}
		$dob       = $birthday ? str_replace('-', '', $birthday) : '';
		$country   = trim(sview::$ctrl['country']);
		$currency  = trim(sview::$ctrl['currency']);
		$country   = strtoupper($country);
		$currency  = strtoupper($currency);
		$account = trim(sview::$ctrl['bankaccount']);
		if ($country == 'CA') {
			$tranum  = trim(sview::$ctrl['tranum']);
			if (!is_numeric($tranum) || strlen($tranum) != 5) {
				sview::$view->assign_error(60031, lang::text(60031));
			}
			$insnum  = sview::$ctrl['insnum'];
			if (!is_numeric($insnum) || strlen($insnum) != 3) {
				sview::$view->assign_error(60032, lang::text(60032));
			}
		} else {
			$tranum = sview::$ctrl['routnum'];
			$insnum = '';
			$ssn    = trim(input::post('ssn'));
			if (!$ssn && $payment['status'] != 1) {
				$view->assign_error(80009, lang::text(80009));
			}
			$last4ssn = substr($ssn, -4);
		}
		//地址信息
		$postalcode = trim(sview::$ctrl['postalcode']);
		$line1      = trim(sview::$ctrl['line1']);
		//验证通过就不要传photo
		$documentid = '';
		$photo  = sview::$ctrl['photo'];
		if ($payment['status'] != 1 && $photo) {
			if (!preg_match("/^data:image\/(.*);base64,/i", substr($photo, 0, 64), $match)) {
				sview::$view->assign_error(60003, lang::text(60003));
			}
			$origin = substr($photo, strlen($match[0]));
			$origin = base64_decode($origin);
			if (!$origin || strlen($origin) > api_uc::MAXSIZE) {
				sview::$view->assign_error(80052, lang::text(80052));
			}
			//上传photo id到stripe返回file-token
			$upfile = config::load('upfile', false);
			$photo  = $upfile['upfile'].'document/';
			if (!is_dir($photo)){
				mkdir($photo, 0777, true) or sview::$view->assign_error(505, lang::text(505));
			}
			$photo  .= $userid.'.jpg';
			$photoid= substr($photo, strlen($upfile['upbase']));
			file_put_contents($photo, $origin);
			$file   = new CurlFile($photo);
			$res    = api_stripepay::document($file);
			if ($res['result'] != '000') {
				sview::$view->assign_error($res['result'], $res['message']);
			}
			$documentid = $res['value']['id'];
		}
		$user      = model::load('live/userinfo')->set_devision($userid)->get_one($userid);
		if ($payment['bank_account'] && $payment['stripeid']) {
			$res = api_stripepay::update_account($user['token'], $payment['stripeid'], $country, $token, $firstname, $lastname,
					$documentid, $dob, $postalcode, $line1, $ssn, $last4ssn, $payment['status']);
		} else {
			$res = api_stripepay::add_account($user['token'], $country, $user['email'], $firstname, $lastname,
					$documentid, $type, $token, $dob, $postalcode, $line1, $ssn, $last4ssn);
		}
		if ($res['result'] != '000') {
			sview::$view->assign_error($res['result'], $res['message']);
		}
		if ($payment['status'] == 1) {
			$field = array('type'=>$type, 'country'=>$country, 'currency'=>$currency, 'bank_account'=>$account,
					'transit_number'=>$tranum, 'instititional_number'=>$insnum, 'postalcode'=>$postalcode, 'line1'=>$line1, 'stime'=>config::$nowtime);
		} else {
			$field = array('type'=>$type, 'first_name'=>$firstname, 'last_name'=>$lastname,'birthday'=>$birthday, 'country'=>$country,
					'currency'=>$currency, 'bank_account'=>$account, 'transit_number'=>$tranum, 'instititional_number'=>$insnum,
					'postalcode'=>$postalcode, 'line1'=>$line1, 'ssn'=>$ssn, 'stripeid'=>$res['value']['userStripeId'], 'stime'=>config::$nowtime);
			if ($documentid) {
				$field['photo_id']   = $photoid;
				$field['documentid'] = $documentid;
			}
		}
		if ($payment) {
			model::load('live/payment')->save($userid, $field);
		} else {
			$field['userid'] = $userid;
			model::load('live/payment')->new_one($field);
		}
		sview::$view->display();
	}
	
	//获取银行卡 3-6-8
	private static function __getcard() {
		$acl    = acl::getinst('vedio');
		$userid = $acl->user['id'];
		$payment= model::load('live/payment')->get_one($userid);
		if ($payment['bank_account']) {
			$data = array('firstname'=>$payment['first_name'], 'lastname'=>$payment['last_name'], 'birthday'=>$payment['birthday'], 
					'country'=>$payment['country'], 'currency'=>$payment['currency'], 'status'=>$payment['status'], 
					'failure'=>$payment['failure'], 'postalcode'=>$payment['postalcode'], 'line1'=>$payment['line1'], 'ssn'=>$payment['ssn']);
			$data['country'] = strtoupper($data['country']);
			if ($data['country'] == 'CA') {
				$data['bankaccount'] = $payment['bank_account'];
				$data['tranum']  = $payment['transit_number'];
				$data['insnum']  = $payment['instititional_number'];
			} else {
				$data['accountnum'] = $payment['bank_account'];
				$data['routnum']    = $payment['transit_number'];
			}
		} else {
			$data = null;
		}
		sview::$view->assign_by_ref('datasets', $data);
		sview::$view->display();
	}
	
	//提现申请 3-6-9
	public function __withdraw() {
		$acl    = acl::getinst('vedio');
		$userid = $acl->user['id'];
		$money  = (int)sview::$ctrl['money'];
		if ($money < self::MIN) {
			sview::$view->assign_error(60036, lang::text(60036));
		}
		//判断主播余额是否够提现
		$anchor = model::load('live/anchor')->get_one($userid);
		$valid  = ($anchor['earningcoins'] - $anchor['depositcoins'])/api_uc::STARRATIO;
		//获取之前已经提现的总额
		$filter = array(1, 2);
		$where  = array('userid'=>$userid, array('status', 2, orm::OP_NE), array('state', 2, orm::OP_NE), array('paystate', $filter, orm::OP_NOTIN), array('paytype', 1, orm::OP_GE));
		$total  = model::load('live/withdraw')->get_total($where, 'sum(money)');
		if (($money + $total/api_uc::CANRATIO) > $valid) {
			sview::$view->assign_error(60035, lang::text(60035));
		}
		//每日最多提取500
		$stime  = strtotime(date('Y-m-d', config::$nowtime));
		$where  = array('userid'=>$userid, array('stime', $stime, orm::OP_GE), array('paytype', 1, orm::OP_GE));
		$total  = model::load('live/withdraw')->get_total($where, 'sum(money)');
		if ($anchor['starlv'] == 4) {
			$max = self::MAX;
		} else {
			$max = self::CMAX;
		}
		if (($money + $total/api_uc::CANRATIO) > $max) {
			sview::$view->assign_error(60036, lang::text(60036));
		}
		$payment= model::load('live/payment')->get_one($userid);
		if (!$payment) {
			sview::$view->assign_error(80122, lang::text(80122));
		}
		//类型 1-银行卡 2-paypal
		$paytype= (int)sview::$ctrl['type'];
		if ($paytype > 2 || $paytype < 1) {
			$paytype = 1;
		}
		if ($paytype == 1 && !$payment['bank_account']) {
			sview::$view->assign_error(80125, lang::text(80125));
		} else if ($paytype == 2 && !$payment['paypal']) {
			sview::$view->assign_error(80124, lang::text(80124));
		}
		$sn     = date('YmdHis').randme::rand_str(6, 2);
		$field  = array('userid'=>$userid, 'paytype'=>$paytype, 'sn'=>$sn, 'type'=>1, 'coins'=>$money*api_uc::STARRATIO,
				'money'=>$money*api_uc::CANRATIO, 'addtime'=>config::$nowtime, 'stime'=>config::$nowtime);
		model::load('live/withdraw')->new_one($field);
		sview::$view->display();
	}
}